﻿using RimWorld;
using System.Collections.Generic;
using Verse;

namespace RimZombieGirl
{
    public class IncidentDefExtension_BuildingSpawn : DefModExtension
    {
        public string buildingDef;     // 要生成的建筑
        public IntRange count;         // 数量范围
    }
    public class IncidentWorker_BuildingSpawn : IncidentWorker
    {
        protected override bool CanFireNowSub(IncidentParms parms)
        {
            return base.CanFireNowSub(parms) && TryFindSpawnCell((Map)parms.target, out _);
        }

        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;
            var ext = def.GetModExtension<IncidentDefExtension_BuildingSpawn>();
            if (ext == null) return false;

            int count = ext.count.RandomInRange;
            ThingDef thingDef = DefDatabase<ThingDef>.GetNamed(ext.buildingDef);

            List<IntVec3> spawnCells = new List<IntVec3>();
            for (int i = 0; i < count; i++)
            {
                if (TryFindSpawnCell(map, out IntVec3 cell))
                {
                    spawnCells.Add(cell);
                    GenSpawn.Spawn(thingDef, cell, map, WipeMode.Vanish);
                }
            }

            if (spawnCells.Count > 0)
            {
                SendStandardLetter(parms, new TargetInfo(spawnCells[0], map));
                return true;
            }

            return false;
        }

        private bool TryFindSpawnCell(Map map, out IntVec3 cell)
        {
            return CellFinderLoose.TryFindRandomNotEdgeCellWith(
                5,
                c => c.Standable(map)
                     && !c.Fogged(map)
                     && c.GetEdifice(map) == null,  // 不覆盖已有建筑
                map,
                out cell);
        }
    }
}
